/*
 * News.java
 * Activity view all stories
 */
package edu.ntu.mobilestomp;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import edu.ntu.helper.StoryList;
import edu.ntu.helper.RestClient;
import edu.ntu.helper.RestClient.RequestMethod;
import edu.ntu.helper.StoryXMLHandler;

public class News extends ListActivity {
	
	private LayoutInflater mInflater;
	private Vector<RowData> data;
	private StoryList allNewsRecords;
	private ArrayList<Integer> allIndex;
	private ArrayList<String> allLink;
	private ArrayList<String> allTitle;
	private ArrayList<String> allDetails;
    private ProgressDialog dialog;
    private CustomAdapter adapter;

	private RowData rd;
	private BitmapFactory.Options options = new BitmapFactory.Options();

	// Data Structure RowData
	private class RowData {
		
		protected int mId;
		protected String mTitle;
		protected String mDetail;
		protected String mLink;
		
		RowData(int id, String title, String detail, String link){
			mId=id;
			mTitle=title;
			mDetail=detail;
			mLink=link;
		}
		
	    @Override
	    public String toString() {
	        return mId+" "+mTitle+" "+mDetail;
	    }
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.simplelist);
		
        // look up the notification manager service
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // cancel the notification that we started in IncomingMessage
        nm.cancel(R.string.upload_ticker);
        options.inSampleSize = 4;

        // Set layout
		mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		data = new Vector<RowData>();
		
		// Show Processing dialog
        showDialog(1);
        
        // AsyncTask to download all the pictures
		new RefreshNewsTask().execute(getString(R.string.base_url)+"/get_all_pics.php");
		
		getListView().setTextFilterEnabled(true);
	}
	
	public void onListItemClick(ListView parent, View v, int position, long id) {        	

		// Set intent to ViewStory Activity when list item is clicked
	
		Intent myIntent = new Intent(v.getContext(), ViewStory.class);
		myIntent.putExtra("storyID", allIndex.get(position));
		
		startActivityForResult(myIntent, 0);
	}
	// Function to get all stories into a list
	private StoryList GetAllNews(String URLPath) {

		StoryList listRecordsT = null;

		RestClient client = new RestClient(URLPath);

		try {
			client.Execute(RequestMethod.GET);
		} catch (Exception e) {
			e.printStackTrace();
		}

		String response = client.getResponse();
		String replacement = null;
		try {

			/** Handling XML */
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();

			/** Create handler to handle XML Tags ( extends DefaultHandler ) */
			StoryXMLHandler myXMLHandler = new StoryXMLHandler();
			xr.setContentHandler(myXMLHandler);
			replacement = response.replace("\n", "");
			replacement = replacement.trim();

			InputSource is = new InputSource(new StringReader(replacement));
			xr.parse(is);

		} catch (Exception e) {
			System.out.println("XML Pasing Excpetion = " + e);
		}

		/** Get result from MyXMLHandler SitlesList Object */
		listRecordsT = StoryXMLHandler.storyList;

		return listRecordsT;
	}

	// Custom Adapter
	private class CustomAdapter extends ArrayAdapter<RowData> {
		
		public CustomAdapter(Context context, int resource, int textViewResourceId, List<RowData> objects) {               
			super(context, resource, textViewResourceId, objects);
		}
		
		
	    @Override
	    public View getView(int position, View convertView, ViewGroup parent) {   
	    	
		    ViewHolder holder = null;
		    TextView title = null;
		    TextView detail = null;
		    ImageView image=null;
		    RowData rowData= getItem(position);
		    
		    if(null == convertView){
	            convertView = mInflater.inflate(R.layout.news, null);
	            holder = new ViewHolder(convertView);
	            convertView.setTag(holder);
	    	}
		    
			holder = (ViewHolder) convertView.getTag();
			title = holder.gettitle();
			title.setText(rowData.mTitle);
			detail = holder.getdetail();
			detail.setText(rowData.mDetail);        
			
			Bitmap bitmap;
			try {
				bitmap = BitmapFactory.decodeStream((InputStream) new URL(getString(R.string.base_url)+ "/uploads/thumbnails/tn_" + rowData.mLink).getContent(), null, options);
				image=holder.getImage();
				image.setImageBitmap(bitmap);
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return convertView;
	    }
	    
        private class ViewHolder {
        	
	        private View mRow;
	        private TextView title = null;
	        private TextView detail = null;
	        private ImageView i11=null; 
	        
	        public ViewHolder(View row) {
	        	mRow = row;
	        }
	        
	        public TextView gettitle() {
	        	
	            if(null == title){
            		title = (TextView) mRow.findViewById(R.id.title);
	            }
	            return title;
	        }     
	        
	        public TextView getdetail() {
	        	if(null == detail){
	        		detail = (TextView) mRow.findViewById(R.id.detail);
                }
	        	return detail;
	        }

	        public ImageView getImage() {
	            if(null == i11){
	            	i11 = (ImageView) mRow.findViewById(R.id.img);
	            }
                return i11;
	        }
        }

   }
	
	// AsyncTask to download News and pictures
	private class RefreshNewsTask extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... path) {
			
			// call GetAllNews function
			allNewsRecords = GetAllNews(path[0]);
		    Log.v("STORY SIZE", allNewsRecords.getSize()+"" );

		    // Assign StoryList array to local variables 
			allIndex = allNewsRecords.getIndex();
			allTitle = allNewsRecords.getTitle();
			allDetails = allNewsRecords.getDetails();
			allLink = allNewsRecords.getLink();
			
			// Looping all stories
			for(int i=0;i<allNewsRecords.getSize();i++){
				try {
					// creating new Row view 
					rd = new RowData(i,allTitle.get(i),allDetails.get(i),allLink.get(i));
				}catch (ParseException e) {
					e.printStackTrace();
				}
				data.add(rd);
			}
	    	adapter = new CustomAdapter(getApplicationContext(), R.layout.simplelist, R.id.title, data);

			return "DOWNLOADED";
		}
		
	    protected void onPostExecute(String result) {
			setListAdapter(adapter);
			dialog.dismiss();
	    }
		
	}
	
	
	// Creating Dialog 
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case 1: {
                dialog = new ProgressDialog(this);
                dialog.setMessage("Please wait while loading...");
                dialog.setIndeterminate(true);
                dialog.setCancelable(true);
                return dialog;
            }
        }
        return null;
    }
}
